package com.ls.hnks.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ls.hnks.common.constant.ScheduleRemindStatusConstant;
import com.ls.hnks.model.ScheduleRemind;
import com.ls.hnks.service.ScheduleRemindService;
import com.ls.hnks.util.SmsClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
@Slf4j
public class SmsScheduled {

    @Autowired
    private SmsClient smsClient;

    @Autowired
    private ScheduleRemindService scheduleRemindService;

    @Scheduled(cron = "0 0/5 * * * ?")
    public void sendScheduleRemind() {
        List<ScheduleRemind> remindList = scheduleRemindService.list(
                new LambdaQueryWrapper<ScheduleRemind>()
                        .eq(ScheduleRemind::getStatus, ScheduleRemindStatusConstant.NOT_SENT)
                        .orderByAsc(ScheduleRemind::getSendtime)
                        .last("limit 100")
        );
        List<ScheduleRemind> updateList = new ArrayList<>();
        SmsClient.Request request = new SmsClient.Request();
        request.setMethod("sms.message.send");
        for (ScheduleRemind remind : remindList) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("mobile", Collections.singletonList(remind.getPhone()));
            jsonObject.put("type", 0);
            jsonObject.put("template_id", "ST_2023041700000009");
            jsonObject.put("sign", "河南科顺");
            jsonObject.put("send_time", remind.getSendtime());
            jsonObject.put("params", "null");
            request.setBizContent(jsonObject.toJSONString());
            String jsonStr = smsClient.execute(request);
            log.info("sms response: {}", jsonStr);
            JSONObject resObj = JSON.parseObject(jsonStr);
            //获取message_id的值
            if (resObj.getIntValue("code") == 0) {
                String messageId = resObj.getJSONObject("data").getJSONObject("result").getString("message_id");
                ScheduleRemind scheduleRemind = new ScheduleRemind();
                scheduleRemind.setId(remind.getId());
                scheduleRemind.setStatus(ScheduleRemindStatusConstant.HAS_BEEN_SENT);
                scheduleRemind.setMessageid(messageId);
                updateList.add(scheduleRemind);
            }
        }
        scheduleRemindService.updateBatchById(updateList);
    }
}
